//
//  OrderTypeView.swift
//  Box
//
//  Created by mn on 2025/3/30.
//

import UIKit
import SnapKit

class OrderTypeView: UIView {

    var tapIndex:(() -> Void)?
    
    private let stackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = 10
        return stackView
    }()
    var selectIndex: Int = 0{
        didSet{
            if selectIndex >= 0, selectIndex < buttons.count {
                let button = buttons[selectIndex]
                buttonTapped(button)
            }
        }
    }
    
    var currentIndex: Int{
        buttons.firstIndex { $0.isSelected } ?? 0
    }

    private var buttons: [UIButton] = []

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        addSubview(stackView)

        stackView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview().offset(-10)
            make.height.equalTo(28)
        }

        for (idx,title) in ["全部", "待发货", "待收货", "已完成", "已取消"].enumerated(){
            let button = UIButton(type: .custom)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
            button.setTitleColor(.fromHex("#5757570"), for: .normal)
            button.setTitleColor(.init(hex: "#B3F832"), for: .selected)
            button.layer.cornerRadius = 14
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
            stackView.addArrangedSubview(button)
            button.tag = idx
            buttons.append(button)
        }
        buttonTapped(buttons.first!)
    }

    @objc private func buttonTapped(_ sender: UIButton) {
        buttons.forEach { button in
            let isSelected = (button == sender)
            button.isSelected = isSelected
            button.backgroundColor = isSelected ? UIColor.black: UIColor.fromHex("#E8E8E8")
        }
        tapIndex?()
    }
}
